package link.ten_fei.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import link.ten_fei.util.ConnectionFactory;

public class ChangePwdDaoImpl implements ChangePwdDao {

	@Override
	public List<String> findUser(String olduser) {
		Connection connection = ConnectionFactory.getConnection();
		PreparedStatement preparedStatement = null;
		ResultSet rs = null;
		try {
			String sql = "select doc_username from doc_user where doc_username=?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, olduser);
			rs = preparedStatement.executeQuery();
			List<String> users = new ArrayList<String>();
			while (rs.next()) {
				users.add(rs.getString("doc_username"));
			}
			return users;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ConnectionFactory.close(connection, preparedStatement, rs);
		}
		return null;
	}

	@Override
	public int changeUserAndPwd(String user, int id, String pwd) {
		// 1.获取数据库连接
		Connection connection = ConnectionFactory.getConnection();
		PreparedStatement preparedStatement = null;
		String sql = null;
		try {
			// 2. 键入sql语句
			if (user != null && id != 0) {
				sql = "update doc_user set doc_username=? where id=?";
				// 3. 获取连接通路
				preparedStatement = connection.prepareStatement(sql);
				// 4. 占位符赋值
				preparedStatement.setString(1, user);

			} else if (id != 0 && pwd != null) {
				sql = "update doc_user set doc_password=? where id=?";
				// 3. 获取连接通路
				preparedStatement = connection.prepareStatement(sql);
				// 4. 占位符赋值
				preparedStatement.setString(1, pwd);
			}
			preparedStatement.setInt(2, id);
			// 5. 执行更新语句
			int flag = preparedStatement.executeUpdate();
			return flag;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ConnectionFactory.close(connection, preparedStatement, null);
		}
		return 0;
	}
}
